<template>
	<div class="system-dept-container">
		<el-dialog title="修改部门" v-model="isShowDialog" >
			<el-form ref="editDeptFormRef" :model="formData" :rules="formRules" label-width="80px">
				<el-row :gutter="35">
					<el-col>
						<el-form-item label="上级部门">
							<el-cascader
								placeholder="请选择上级部门（可选填）"
								v-model="formData.parentId"
								:options="depts"
								:props="{expandTrigger: 'hover', emitPath: false, checkStrictly: true, value: 'id', label: 'deptName', children: 'children' }"
								class="w100"
								clearable>
							</el-cascader>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="部门名称" prop="deptName">
							<el-input v-model="formData.deptName" placeholder="请输入部门名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="部门状态" prop="status">
							<el-select v-model="formData.status" placeholder="请选择部门状态" clearable class="w100">
								<el-option label="正常" value="0"></el-option>
								<el-option label="停用" value="1"></el-option>
								<el-option label="删除" value="2"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="负 责 人" prop="leaderId">
							<!-- <el-input v-model="formData.leader" placeholder="请输入部门负责人" clearable></el-input> -->
							 <el-select v-model="formData.leaderId" filterable remote 
								@click="loadUsers()"
								@change="onLeaderChange"
                                :remote-method="loadUsers"
								placeholder="请选择部门负责人" clearable class="w100">
								<el-option
									v-for="item in users"
									:key="item.id"
									:label="`${item.userName} / ${item.loginName}`"
									:value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="联系电话" prop="phone">
							<el-input v-model="formData.phone" placeholder="请输入联系电话" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="邮箱账号" prop="email">
							<el-input v-model="formData.email" placeholder="请输入邮箱账号" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="部门排序" prop="orderNum">
							<el-input-number v-model="formData.orderNum" :min="0" :max="999" clearable class="w100"></el-input-number>
						</el-form-item>
					</el-col>
					<el-col>
						<el-form-item label="备注">
							<el-input type="textarea" v-model="formData.remark" placeholder="请输入备注" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel">取 消</el-button>
					<el-button type="primary" @click="onSubmit">保 存</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts">
import { reactive, toRefs, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getDeptList, editDept } from '/@/api/system/dept/index';
import { getUserList } from '/@/api/system/user/index';
import { verifyPhone, verifyEmail } from '/@/utils/toolsValidate';
import { lineToTreeData } from '/@/utils/commonFunction';
export default {
	name: 'dept/edit',
	setup(props, context) {
		const editDeptFormRef = ref();
		const validPhone = (rule, value, callback) => {
			if(!value){
				return callback(new Error('手机号码不能为空'));
			}
			if(value.indexOf('*') == -1 && !verifyPhone(value)){
				return callback(new Error('请输入正确格式的手机号码'));
			}
			return callback();
		}
		const validEmail = (rule, value, callback) => {
			if(!value){
				return callback(new Error('邮箱账号不能为空'));
			}
			if(value.indexOf('*') == -1 && !verifyEmail(value)){
				return callback(new Error('请输入正确格式的邮箱账号'));
			}
			return callback();
		}

		const state = reactive({
			isShowDialog: false,
			depts: [],
			users: [],
			formData: {},
			formRules : {
				status: { required: true, message: '部门状态不能为空', trigger: 'change' },
				deptName: { required: true, message: '部门名称不能为空', trigger: 'blur' },
				phone: { validator: validPhone, trigger: 'blur' },
				email: { validator: validEmail, trigger: 'blur' },
				orderNum: { required: true, message: '部门排序不能为空', trigger: 'blur' }
			}
		});
		//初始化上级部门级联
		const loadDepts = async () => {
			await getDeptList().then((res) => {
				if(res.code == 0){
					state.depts = lineToTreeData(res.data);
				}
			});
		}
		//获取用户
		const loadUsers = async (query?: string) => {
			await getUserList({userName: query}).then((res) => {
				if(res.code == 0){
					state.users = res.data;
				}
			});
		}
		// 负责人选择
		const onLeaderChange = (value) => {
			const user = state.users.find(item => item.id == value);
			state.formData.leader = user ? user.userName : ''
			state.formData.phone = user ? user.phone : '';
			state.formData.email = user ? user.email : '';
		}
		// 打开弹窗
		const openDialog = (row: any) => {
			state.isShowDialog = true;
			if(row){
				state.formData = Object.assign({}, row);
				state.users.push({id: row.leaderId, userName: row.leader, loginName: ''});
			}
			loadDepts();
		};
		// 关闭弹窗
		const closeDialog = (row?: object) => {
			state.isShowDialog = false;
			for(var key in state.formData) {
				state.formData[key] = undefined;
			}
			editDeptFormRef.value.resetFields();
		};
		// 取消
		const onCancel = () => {
			closeDialog();
		};
		// 保存
		const onSubmit = () => {
			editDeptFormRef.value.validate(valid => {
				if(valid){
					let params = {
						id: state.formData.id,
						parentId: state.formData.parentId,
						status: state.formData.status,
						deptName: state.formData.deptName,
						leaderId: state.formData.leaderId,
						leader: state.formData.leader.indexOf('*') > -1 ? undefined : state.formData.leader,
						phone: state.formData.phone.indexOf('*') > -1 ? undefined : state.formData.phone,
						email: state.formData.email.indexOf('*') > -1 ? undefined : state.formData.email,
						orderNum: state.formData.orderNum,
						remark: state.formData.remark
					}
					editDept(params).then((res) => {
						if(res.code === 0){
							ElMessage.success('保存成功');
							context.emit('submit');
							closeDialog(); // 关闭弹窗
						}
					});
				}
			});
		};
		
		return {
			editDeptFormRef,
			openDialog,
			closeDialog,
			loadUsers,
			onLeaderChange,
			onCancel,
			onSubmit,
			...toRefs(state),
		};
	},
};
</script>
